package com.xindaoapp.henghua.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.henghua.R;
import com.xindaoapp.henghua.activity.ImagePagerActivity;
import com.xindaoapp.henghua.application.XinDaoApplication;
import com.xindaoapp.henghua.bean.DeviceScanDatas;
import com.xindaoapp.henghua.entry.Photos;
import com.xindaoapp.henghua.entry.PropertyGatherInfo;
import com.xindaoapp.henghua.entry.PropertyLabelInfo;
import com.xindaoapp.henghua.entry.ScanData;
import com.xindaoapp.henghua.utils.CommFunc;
import com.xindaoapp.henghua.utils.UpdateDataChanged.OnUpdateDataChangedListener;

public class PhotoFragment extends XDBaseFragment {

	private final String TAG = "PhotoFragment";

	private GridView gv_photo;
	private TextView tv_photoNums;

	/** 获取设备相关所有信息*/
	private PropertyGatherInfo info = null;

	private List<DeviceScanDatas> deviceData;
	private List<Map<String, String>> dataList;

	private String deviceID = "";

	private final OnUpdateDataChangedListener mOnUpdateDataChangedListener = new OnUpdateDataChangedListener() {

		@Override
		public void onUpdateDataChanged() {

			info = XinDaoApplication.get().getUpdateDataChanged().getPropertyGatherInfo(deviceID);

			if (null != info) {
				initData();
			}

		}
	};

	public static PhotoFragment newInstance(Bundle args) {

		final PhotoFragment f = new PhotoFragment();

		f.setArguments(args);

		return f;
	}

	@Override
	protected void initUi() {
		gv_photo = (GridView) findViewById(R.id.gv_ptoto);
		tv_photoNums = (TextView) findViewById(R.id.photoNums);

		gv_photo.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				Intent intent = new Intent(getActivity(), ImagePagerActivity.class);
				intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, (Serializable) dataList);
				intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
				getActivity().startActivity(intent);
			}
		});
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.d(TAG, "onCreate");

		XinDaoApplication.get().getUpdateDataChanged().add(mOnUpdateDataChangedListener);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		Log.d(TAG, "onCreateView");

		mView = inflater.inflate(R.layout.fragment_photo, container, false);
		return mView;
	}

	public List<String> breviaryphotos;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		Log.d(TAG, "onActivityCreated");

		info = (PropertyGatherInfo) getArguments().getSerializable("info");

		deviceID = info.id;

		if (info.propertyLabelInfos != null) {

			initData();

		} else {
			System.out.println("info.propertyWithLabelDataInfo == null");
			CharSequence text = getString(R.string.detail_photo_above, 0);
			tv_photoNums.setText(text);
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		XinDaoApplication.get().getUpdateDataChanged().remove(mOnUpdateDataChangedListener);
	}

	private void initData() {
		getData();
		sortDevice();

		if (deviceData.size() != 0) {

//			System.out.println("conut ====== " + deviceData.size());

			CharSequence text = getString(R.string.detail_photo_above, deviceData.size());
			tv_photoNums.setText(text);

			MyAdapter adapter = new MyAdapter(getActivity(), deviceData);
			gv_photo.setAdapter(adapter);
		} else {
			CharSequence text = getString(R.string.detail_photo_above, 0);
			tv_photoNums.setText(text);
		}
		for (DeviceScanDatas deviceScan : deviceData) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("uri", deviceScan.photphoto);
			dataList.add(map);
		}

	}

	/**
	 * 对照片按照时间倒序排序
	 */
	private void sortDevice() {
		Collections.sort(deviceData, new Comparator<DeviceScanDatas>() {

			@Override
			public int compare(DeviceScanDatas lhs, DeviceScanDatas rhs) {
				return rhs.scan_time.compareTo(lhs.scan_time);
			}
		});
	}

	private void getData() {

		deviceData = new ArrayList<DeviceScanDatas>();
		dataList = new ArrayList<Map<String, String>>();

		if (info.scanDatas == null) {
			return;
		}

		List<ScanData> scanDataList = info.scanDatas;

		if (scanDataList != null) {
			for (int i = 0; i < scanDataList.size(); i++) {
				ScanData scanData = scanDataList.get(i);

				Photos photos = scanData.photos;

				if (photos.photphotos == null || photos.breviaryphotos == null) {
					continue;
				}

				for (int j = 0; j < photos.breviaryphotos.size(); j++) {

					System.out.println("size === " + photos.breviaryphotos.size());

					DeviceScanDatas deviceScanData = new DeviceScanDatas();

					deviceScanData.setId(scanData.id);
					deviceScanData.setTag_code(scanData.tag_code);
					deviceScanData.setScan_time(scanData.scan_time);
					deviceScanData.setScan_location_gps(scanData.scan_location_gps);
					deviceScanData.setScan_location(scanData.scan_location);
					deviceScanData.setScan_device(scanData.scan_device);
					deviceScanData.setScan_devicename(scanData.scan_devicename);
					deviceScanData.setStatus(scanData.status);
					deviceScanData.setBreviaryphoto(photos.breviaryphotos.get(j));
					deviceScanData.setPhotphoto(photos.photphotos.get(j));

					deviceScanData.setPart(getPart(scanData.tag_code));
					

					
					deviceData.add(deviceScanData);

				}
			}
		}

	}

	/**
	 * 获取贴签部位
	 * @param tag_code
	 * @return
	 */
	private String getPart(String tag_code) {

		List<PropertyLabelInfo> data = info.propertyLabelInfos;

		for (int i = 0; i < data.size(); i++) {
			PropertyLabelInfo propertyLabelInfo = data.get(i);
			String code = propertyLabelInfo.tag_code;
			if (code.equals(tag_code)) {
				return propertyLabelInfo.part;
			}
		}

		return "";
	}

	private class MyAdapter extends BaseAdapter {

		private final Context mContext;
		private final List<DeviceScanDatas> mData;

		MyAdapter(Context context, List<DeviceScanDatas> data) {
			this.mContext = context;
			this.mData = data;
		}

		@Override
		public int getCount() {
			return mData == null ? 0 : mData.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("NewApi")
		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			ViewHolder holder = null;
			if (null == convertView) {
				holder = new ViewHolder();
				convertView = View.inflate(mContext, R.layout.fragment_photo_item, null);
				holder.photo = (ImageView) convertView.findViewById(R.id.side_photo_photo);
				holder.time = (TextView) convertView.findViewById(R.id.side_photo_time);
				holder.place = (TextView) convertView.findViewById(R.id.side_photo_place);
				holder.state = (TextView) convertView.findViewById(R.id.side_photo_state);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			DeviceScanDatas item = mData.get(position);
			String str = "";

			str = item.status;
			if (!TextUtils.isEmpty(str)) {
				holder.state.setText(str);
			}

			String time = CommFunc.getTime(item.scan_time);
			str = time;

			if (!TextUtils.isEmpty(str)) {
				holder.time.setText(str);
			}
			str = item.part;
			if (!TextUtils.isEmpty(str)) {
				holder.place.setText(str);
			}

			str = item.breviaryphoto;
			if (!TextUtils.isEmpty(str)) {
				ImageLoader.getInstance().displayImage(str, holder.photo);
			}

			return convertView;
		}
	}

	class ViewHolder {
		ImageView photo;
		TextView time, place, state;
	}

}
